
var viewModel = new function () {
    this.productList = ko.observableArray();
    this.ProductCount = ko.observable(0);
    
    this.existProduct = ko.computed(function () {
        if(this.productList().length > 0) return true;
		return false;
    }, this);
    
    /////////////////////////////////////////////////////////////////
    ///////////////////// Get data from server //////////////////////
    /////////////////////////////////////////////////////////////////
    var dataPost = {};
    // Class to represent a row in the table products
    // Name : ten sp
    // ImagePath : PicUrl
    // Type : Nhom loai sp ()
    // Price : Gia tham khao
    // PriceDiscount : Gia khuyen mai
    // Vendor : Hang san xuat
    // MadeIn : Noi san xuat
    // Gift :Quà tăng (null: ko có quà)
    // Còn hàng:_IsStocking (1 còn hàng)
    function ProductItem(   _Id, _Name, _Seri, _ImagePath, _TypeId, _TypeName, _Price, 
                            _PriceDiscount, _VendorId, _VendorName, _MadeInId, _MadeInName, 
                            _ChietKhau, _IsNew, _Gift, _IsStocking) {
        this.Id = _Id;
        this.Name = _Name;
        this.Seri = _Seri;
        this.ImagePath = _ImagePath;
        this.TypeId = _TypeId;
        this.TypeName = _TypeName;
        this.Price = _Price;
        this.PriceFormat = formatCurrency("#.##0,#", _Price) + " VNĐ";
        this.PriceDiscount = _PriceDiscount;
        this.PriceDiscountFormat = formatCurrency("#.##0,#", _PriceDiscount) + " VNĐ";
        this.VendorId = _VendorId;
        this.VendorName = _VendorName;
        this.MadeInId = _MadeInId;
        this.MadeInName = _MadeInName;
        this.Link = "Detail.aspx?type=getbyid&id=" + _Id;
        
        this.ChietKhau = ko.computed(function () {
            if (_ChietKhau.toString() != "0") return _ChietKhau.toString() + "%";
            else return "";
        }, this);   
        
        this.SaleClass = ko.computed(function () {
            if (_ChietKhau.toString() != "0") return "pis-item";
            else return "pis-km2";
        }, this);
        
        this.GiftClass = ko.computed(function () {
            if (_Gift != null && _Gift != "" && _IsStocking == "1") return "pis-km2";
            else return "";
        }, this);
        
        this.NewClass = ko.computed(function () {
            if (_IsNew.toString() == "1") return "ico_moi_small showInList";
            else return "";
        }, this);
        this.StockingClass = ko.computed(function () {
            if (_IsStocking == "0") return "pi-hethang";
            else return "";
        }, this);
    }
    var urlPost;
    
    var keyword = getURLParameter('keyword').toString();
    $("#keywordString").text(keyword);
    urlPost = "but/ajax/Search.aspx?type=name&keyword=" + keyword;
    
    writeLog(urlPost);
    // Json Get function to retrive returnData from server
    $.ajax({ type: "POST", url: urlPost, returnData: dataPost, dataType: "json",
        success: function (returnData, textStatus, jqXHR) {
            if(returnData.length > 0) {
                //writeLog(returnData);
                for(var i=0; i<returnData.length; i++) {
                    viewModel.productList.push(new ProductItem(  
                                                            returnData[i].Id,
                                                            returnData[i].TenHang,
                                                            returnData[i].Seri, 
                                                            returnData[i].PicUrl.replace("_s.",".").replace("../",""),
                                                            returnData[i].LoaiId,
                                                            returnData[i].LoaiId,
                                                            returnData[i].GiaBanThamKhao,
                                                            returnData[i].GiaBanCoChietKhau,
                                                            returnData[i].NhomId,
                                                            returnData[i].TenNhom,
                                                            returnData[i].NoiSxid,
                                                            returnData[i].TenNoiSx,
                                                            returnData[i].ChietKhau,
                                                            returnData[i].HangMoi,
                                                            returnData[i].QuaTang,
                                                            returnData[i].ConHang));
                }
                //dataList = viewModel.productList();
                viewModel.ProductCount(viewModel.productList().length);
                $("#NoSearchWereFound").text("");
            }
            else writeLog("search data-sp is null");
            
        },
        error: function (xhr, status, error) {

        }
    });  // End ajax post

	// Properties of dropdownlist
	function OptionItem(_Id, _Name) {
		this.Id = _Id;
		this.Name = _Name;
	}
	this.OrderOptions = ko.observableArray();
	this.OrderOptions.push(new OptionItem("price_asc", "Giá tăng dần"));
	this.OrderOptions.push(new OptionItem("price_desc", "Giá giảm dần"));
	this.OrderOptions.push(new OptionItem("name_asc", "Từ A đến Z"));
	this.OrderOptions.push(new OptionItem("name_desc", "Từ Z đến A"));
	this.selectOrderId = ko.observable();
	
	this.ShowOptions = ko.observableArray();
	this.ShowOptions.push(new OptionItem(6, "6"));
	this.ShowOptions.push(new OptionItem(9, "9"));
	this.ShowOptions.push(new OptionItem(10, "10"));
	this.ShowOptions.push(new OptionItem(15, "15"));
	this.ShowOptions.push(new OptionItem(20, "20"));
	this.ShowOptions.push(new OptionItem(50, "50"));
	this.ShowOptions.push(new OptionItem(75, "75"));
	this.ShowOptions.push(new OptionItem(100, "100"));
	this.selectShowId = ko.observable(9);
	
	this.selectOrderChanged = function(event) {
		sorting();
    }
	this.selectShowChanged = function(event) {
		this.PageSize(this.selectShowId());
		if(viewModel.productList().length > 0)
			this.CurrentPageIndex(1);
		else
			this.CurrentPageIndex(0);
    }
    
    /////// PAGING ////////
	this.PageSize = ko.observable(9);
    this.MaxPageIndex = ko.computed(function () {
        return Math.ceil(ko.utils.unwrapObservable(this.productList().length / this.PageSize()));
    }, this);
    this.CurrentPageIndex = ko.observable(1);
	this.itemsOnCurrentPage = ko.computed(function () {
        var pagevalue = this.PageSize().toString().replace(/\s/g, ''),
			pagesize = parseInt(pagevalue, 10);

        if (isNaN(pagesize) || pagesize < 1 || pagesize > 100) {
            return "";
        }
        else {
            var startIndex = this.PageSize() * (this.CurrentPageIndex() - 1),
				endIndex = parseInt(startIndex) + parseInt(this.PageSize());

            return this.productList.slice(startIndex, endIndex);
        }
    }, this);
	this.existProduct = ko.computed(function () {
        if(this.productList().length > 0){
            $("#NoSearchWereFound").text("");
            return true;
        }
		else {
		    $("#NoSearchWereFound").text("Không tìm được sản phẩm nào phù hợp nội dung tìm kiếm.");
		    return false;
		}
    }, this);
	
    this.ProductCount = ko.observable(this.productList().length);
    
	// Paginate
    this.PreviousPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            this.CurrentPageIndex(page - 1);
        }
    }
    this.PrevButtonClass = ko.computed(function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            return "btn-image btn-prev-arrow prev-active";
        }
        else {
            return "btn-image btn-prev-arrow";
        }
    }, this);

    this.NextPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page < this.MaxPageIndex()) {
            this.CurrentPageIndex(page + 1);
        }
    }
    this.NextButtonClass = ko.computed(function () {
        if (this.CurrentPageIndex() == this.MaxPageIndex() || this.MaxPageIndex() == 1)
            return "btn-image btn-next-arrow next-disabled";
        else
            return "btn-image btn-next-arrow";
    }, this);
};

ko.applyBindings(viewModel, document.getElementById('viewList'));

function RefreshProductList(data) {
	viewModel.productList(data);
	viewModel.ProductCount(viewModel.productList().length);
	sorting();
	if(viewModel.productList().length > 0)
		viewModel.CurrentPageIndex(1);
	else
		viewModel.CurrentPageIndex(0);
} 
// sort all items
function SortByPropertyName(items, propertyName, sortOrder) {
	return items.sort(sortProperty(propertyName, sortOrder));
}
function sortProperty(property, sortOrder) {
	if (sortOrder == "asc") {
		return function (a, b) {
			if ($.isNumeric(a[property]) && $.isNumeric(b[property])) {
				return (parseFloat(a[property]) < parseFloat(b[property])) ? -1 : (parseFloat(a[property]) > parseFloat(b[property])) ? 1 : 0;
			}
			else {
				if (isDateTime(a[property]) && isDateTime(b[property])) {
					return (parseDateTime(a[property]) < parseDateTime(b[property])) ? -1 : (parseDateTime(a[property]) > parseDateTime(b[property])) ? 1 : 0;
				} else {
					return (a[property].toLowerCase() < b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() > b[property].toLowerCase()) ? 1 : 0;
				}
			}
		}
	}
	else {
		return function (a, b) {
			
			if ($.isNumeric(a[property]) && $.isNumeric(b[property])) {
				return (parseFloat(a[property]) > parseFloat(b[property])) ? -1 : (parseFloat(a[property]) < parseFloat(b[property])) ? 1 : 0;
			}
			else {
				if (isDateTime(a[property]) && isDateTime(b[property])) {
					return (parseDateTime(a[property]) > parseDateTime(b[property])) ? -1 : (parseDateTime(a[property]) < parseDateTime(b[property])) ? 1 : 0;
				} else {
					return (a[property].toLowerCase() > b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() < b[property].toLowerCase()) ? 1 : 0;
				}
			}

		}
	}
}

function scrollToTop() {
    $(document).scrollTop(0);
}


